﻿using SharpDX;
using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.Text;

namespace SpaceBattle
{
    class MouseInput
    {
        private List<Vector2> Positions = new List<Vector2>();
        private int MaxPositionsCount = 255;
        private RenderForm window = null;

        private bool isLeftButtonDown = false;
        private bool isLeftButtonUp = true;
        private bool isClicked = false;

        public MouseInput(RenderForm window)
        {
            this.window = window;
            Positions.Add(GetCurrentMousePosition());
        }

        public void Update(object sender, SharpDX.RawInput.MouseInputEventArgs args)
        {
            if (Positions.Count > MaxPositionsCount)
                Positions.RemoveAt(0);

            //if (args.X != 0 && args.Y != 0)
            //    Positions.Add(Positions[Positions.Count - 1] + new Vector2(args.X, args.Y));

            if (args.X != 0 && args.Y != 0)
                Positions.Add(GetCurrentMousePosition());

            if (args.ButtonFlags == SharpDX.RawInput.MouseButtonFlags.LeftButtonDown)
            {
                isLeftButtonDown = true;
                isLeftButtonUp = false;
            }

            if (args.ButtonFlags == SharpDX.RawInput.MouseButtonFlags.LeftButtonUp)
            {
                isLeftButtonUp = true;
            }

            CheckIfLeftButtonClicked();
            
        }

        private void CheckIfLeftButtonClicked()
        {
            if (isLeftButtonDown && isLeftButtonUp)
            {
                isClicked = true;
                // reset internals
                isLeftButtonDown = false;
            }
        }

        private Vector2 GetCurrentMousePosition()
        {
            var point = this.window.PointToClient(System.Windows.Forms.Control.MousePosition);
            return new Vector2(point.X, point.Y);
        }

        public Vector2 GetLastMousePosition()
        {
            return Positions[Positions.Count - 1];
        }

        public bool IsClicked()
        {
            if (isClicked)
            {
                isClicked = false;
                return true;
            }
            return false;
        }
    }
}
